import Taro from "@tarojs/taro";
import crypto from "crypto-js";
import { Base64 } from "js-base64";

const accessKeyId = "LTAI5tHJwXxSXpzvWc2fyrqX";
const accessKeySecret = "kMTdTE7CNv12QimR6TNUcFrvbTPmyr";
const host = "https://bbs-xk.oss-cn-chengdu.aliyuncs.com";

// 计算签名
function computeSignature(accessKeySecret: string, canonicalString: string) {
  return crypto.enc.Base64.stringify(
    crypto.HmacSHA1(canonicalString, accessKeySecret)
  );
}

// 计算policy
function computePolicy() {
  const date = new Date();
  date.setHours(date.getHours() + 1);
  
  const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
      ["content-length-range", 0, 1024 * 1024 * 1024], // 限制上传大小。
    ],
  };
  return Base64.encode(JSON.stringify(policyText)); // policy必须为base64的string。
}

const policy = computePolicy();
const signature = computeSignature(accessKeySecret, policy);
// console.log(policy)

/**
 * 小程序直传oss
 * @param file 
 */
export async function uploadFileOss(tempFilePath: string) {
  const fileName = tempFilePath.split("tmp/").pop();
  return new Promise<string>((resolve, reject) => {
    Taro.uploadFile({
      url: host,
      filePath: tempFilePath,
      name: "file", // 必须填file。
      formData: {
        key: fileName,
        policy,
        OSSAccessKeyId: accessKeyId,
        signature,
      },
      success: (res) => {
        if (res.statusCode === 204) {
          console.log("上传成功");
          resolve(host + "/" + fileName);
        }
      },
      fail: (err) => {
        console.log(err);
        reject(err);
      },
    });
  });
}

//Taro.chooseImage.ImageFile 对象读成 ArrayBuffer
// Taro.getFileSystemManager().readFile({
//   filePath: file.path,
//   success: (result) => {
//     console.log(result);
//   },
// });

//选择文件
// const openFile = async () => {
//   const result = await Taro.chooseImage({
//     count: 2,
//     sizeType: ["original", "compressed"],
//     sourceType: ["album", "camera"],
//   });

//   for (let file of result.tempFiles) {
//     console.log(file);
//     const url = await uploadFileOss(file);
//     console.log(url);
//   }
// };
